export default {
  namespaced: true,
  state: {
    source: 'kuwo',
    // 是否加载中
    loading: false,
    // 歌单
    songList: [],
    // 歌曲总数
    totalCount: 0,
    // 歌单缓存
    songListCache: {},
    // 当前页数
    page: 0,
    // keyword
    keyword: ''
  },
  mutations: {
    setState(state, option) {
      for (const key in option) {
        state[key] = option[key]
      }
    }
  },
  actions: {
    // 获取搜索结果
    search(state, { keyword }) {
      // 如果又keyword，可能是重新搜索了
      if (keyword) {
        state.state.keyword = keyword
        // 默认第一页
        state.state.page = 1
      }
      // 缓存ID
      let cacheId = state.state.keyword + '_' + state.state.page

      return new Promise((resolve, reject) => {
        // 查看缓存
        if (state.state.songListCache[cacheId]) {
          return state.state.songList = state.state.songListCache[cacheId]
        }

        fetch(`http://iecoxe.top:5000/v1/kuwo/search?key=${state.state.keyword}&limit=30&offset=${state.state.page}`).then(_ => _.json()).then(result => {
          if (result.code === 200) {
            // 获取歌曲搜索总数
            state.state.totalCount = Number(result.data.total)
            // 选出真正所需的歌曲信息
            let songListData = result.data.list.map(item => {
              return {
                ...item,
                imgsrc: item['pic120'],
                source: state.state.source
              }
            })
            // 设置歌单
            state.state.songList = songListData
            // 缓存歌单
            state.state.songListCache[cacheId] = songListData
            resolve()
          }
        }).catch(err => reject(err))
      })
    },

    // 获取搜索建议
    suggestSearch(state, keyword) {
      return new Promise((resolve, reject) => {
        fetch(`http://iecoxe.top:5000/v1/kuwo/suggestSearch?key=${keyword}`)
          .then(_ => _.json())
          .then(result => {
            if (result.code === 200) {
              resolve(result.data.map(item => {

                return { value: item && item.split('=')[1] && item.split('=')[1].split('\r')[0] }
                // return { value: item?.split('=')[1]?.split('\r')[0] }
              }))
            }
          })
          .catch(err => reject(err))
      })
    },

    // 获取播放地址
    getMusicUrl(state, id) {
      return new Promise((resolve, reject) => {
        fetch(`http://iecoxe.top:5000/v1/kuwo/song?rid=${id}`)
          .then((_) => _.json())
          .then((result) => {
            // 服务器找不到播放地址
            if (result.code === "Song:url_notfound") reject("Song:url_notfound")
            resolve(result)
          })
          .catch(err => reject(err))
      })
    },

    // 获取歌词
    getLyric(state, id) {
      return new Promise((resolve, reject) => {
        fetch(`http://iecoxe.top:5000/v1/kuwo/lyric?from=pc&rid=${id}`).then(_ => _.json())
          .then(res => resolve(res.lyric_str))
          .catch(err => reject(err))
      })
    },

    // 监听换页
    changePage(state, page) {
      // 更新页数
      state.state.page = page
      state.dispatch('search', {})
    }


  }
}
